﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace IndividualClient
{
    public partial class FileRequester : Form
    {
        public FileRequester()
        {
            InitializeComponent();
        }

        private void searchBox_TextChanged(object sender, EventArgs e)
        {
            SubSonic.Query q = new SubSonic.Query("file").WHERE("name LIKE %" + searchBox.Text + "%");
            DataSet ds = q.ExecuteDataSet();
            if (searchBox.Text == "")
                searchResults.DataSource = null;
            else
                searchResults.DataSource = ds.Tables[0];
        }

        private void FileRequester_Load(object sender, EventArgs e)
        {
            indexWorker.WorkerReportsProgress = true;
            formLoadOperations.RunWorkerAsync();
            dirsToIndex.DataSource = new SubSonic.Generated.IndexCollection().Load();
        }

        #region formLoadOperations
        private void formLoadOperations_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            numIndexed.Text = e.Result.ToString();
        }

        private void formLoadOperations_DoWork(object sender, DoWorkEventArgs e)
        {
            e.Result = new SubSonic.Query("file").GetCount("name");
        }
        #endregion

        #region IndexStuff
        private void addDirToList_Click(object sender, EventArgs e)
        {

        }

        private void removeDirFromList_Click(object sender, EventArgs e)
        {

        }

        #region BuildIndex Events
        private void buildIndex_Click(object sender, EventArgs e)
        {

        }

        private void indexWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            SubSonic.DeleteQuery del = new SubSonic.DeleteQuery("file");
            del.Execute();
            del = new SubSonic.DeleteQuery("metadata");
            del.Execute();
            List<string> allFiles = new List<string>();
            foreach (DirectoryInfo d in ((IndexStateInfo)e.Argument).Dirs)
            {
                foreach (string s in Directory.GetFiles(d.FullName, "*.*", SearchOption.AllDirectories))
                {
                    allFiles.Add(s);
                }
            }

            double fileCount = allFiles.Count;
            double percent = 100f / fileCount;
            double sum = 0f;

            FileInfo f;
            SubSonic.Generated.File file;
            SubSonic.Generated.Metadatum md;
            IndexStateInfo si = new IndexStateInfo();
            TagLib.File tl;
            foreach (string s in allFiles)
            {
                f = new FileInfo(s);
                file = new SubSonic.Generated.File();
                md = new SubSonic.Generated.Metadatum();


                md.MarkNew();
                if (f.Extension.ToLower() == ".mp3")
                {
                    try
                    {
                        tl = TagLib.File.Create(f.FullName);
                        md.Album = tl.Tag.Album;
                        if (tl.Tag.Performers.Length > 0)
                            md.Artist = tl.Tag.Performers[0];
                        md.Bitrate = tl.Properties.AudioBitrate;
                        if (tl.Tag.Composers.Length > 0)
                            md.Composer = tl.Tag.Composers[0];
                        md.Duration = tl.Properties.Duration.ToString();
                        if (tl.Tag.Genres.Length > 0)
                            md.Genre = tl.Tag.Genres[0];
                        md.Title = tl.Tag.Title;
                        md.Track = tl.Tag.Track;
                        md.Year = tl.Tag.Year;
                    }
                    catch //(CorruptFileException corr)
                    {
                        goto treatAsNormalFile;
                    }
                }
                else if (f.Extension.ToLower() == ".avi")
                {
                    try
                    {
                        tl = TagLib.File.Create(f.FullName);
                        md.Height = tl.Properties.VideoHeight;
                        md.Width = tl.Properties.VideoWidth;
                        md.Duration = tl.Properties.Duration.ToString();
                    }
                    catch
                    {
                        goto treatAsNormalFile;
                    }
                }
            treatAsNormalFile:
                md.Bytesize = f.Length.ToString();
                md.Save();

                si.Percent = percent;
                sum += percent;
                indexWorker.ReportProgress(Convert.ToInt32(sum), si);

                file.MarkNew();
                file.Name = f.Name;
                file.Metadataid = (long)md.GetPrimaryKeyValue();
                file.Path = f.DirectoryName;
                file.Extension = f.Extension;
                file.Save();

                md = null;
                file = null;
                f = null;
                tl = null;
            }
        }

        private void indexWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            progPercent.Text = (Convert.ToDouble(progPercent.Text) + ((IndexStateInfo)e.UserState).Percent).ToString();
            prog.Value = e.ProgressPercentage;
        }

        private void indexWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            numIndexed.Text = new SubSonic.Query("file").GetCount("name").ToString();
        }
        #endregion

        private void listReset_Click(object sender, EventArgs e)
        {

        }
        #endregion

        private void searchBox_TextChanged_1(object sender, EventArgs e)
        {
            SubSonic.Query q = new SubSonic.Query("file").WHERE("name LIKE %" + searchBox.Text + "%");
            DataSet ds = q.ExecuteDataSet();
            if (searchBox.Text == "")
                searchResults.DataSource = null;
            else
            {
                searchResults.DataSource = ds.Tables[0];
                searchResults.Columns[0].Visible = false;
                searchResults.Columns[2].Visible = false;
                searchResults.Columns[3].Visible = false;
                searchResults.Columns[4].Visible = false;
                searchResults.Columns[1].Width = (searchResults.Width - 80);
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            SELECTEDFILE = searchResults.SelectedRows[0].Cells[3].Value.ToString() + @"\" + searchResults.SelectedRows[0].Cells[1].Value.ToString();
            Close();
        }
        public string SELECTEDFILE = "";

        private void btnSelect_Click(object sender, EventArgs e)
        {

        }

        private void FileRequester_ResizeEnd(object sender, EventArgs e)
        {
            //if(searchResults.Width > 80)
                //searchResults.Columns[1].Width = searchResults.Width - 80;
        }
    }
}
